package priv.chenkai.spring_cli.service;

import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import priv.chenkai.spring_cli.dao.UserDao;
import priv.chenkai.spring_cli.exception.ReadMessageException;
import priv.chenkai.spring_cli.model.User;
import priv.chenkai.spring_cli.util.BeanUtil;
import priv.chenkai.spring_cli.util.DateTime;
import priv.chenkai.spring_cli.util.Pair;
import priv.chenkai.spring_cli.vo.UserVo;

import java.util.Collections;
import java.util.List;

/**
 * 用户服务
 * Created by chenkai on 2018/1/8.
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 查询用户列表
     * @param start
     * @param limit
     * @return
     */
    public Pair<List<UserVo>,Integer> find(Integer start, Integer limit){
        int total = userDao.count();
        if(total == 0){
            return Pair.makePair(Collections.emptyList(),0);
        }
        List<User> list = userDao.find(start, limit);
        List<UserVo> users = Lists.newArrayList();
        list.forEach(e-> users.add(BeanUtil.toVo(e)));
        return Pair.makePair(users,total);
    }

    /**
     * 新增用户
     * @param vo
     * @return
     */
    public int insert(UserVo vo){
        if(vo == null){
            return 0;
        }
        User user = BeanUtil.toPo(vo);
        user.setCreateTime(DateTime.getCurrTime());
        user.setUpdateTime(user.getCreateTime());
        int count = userDao.insert(user);
        return count;
    }

    /**
     * 更新用户
     * @param vo
     * @return
     */
    public int update(UserVo vo){
        if(vo == null){
            return 0;
        }
        User user = BeanUtil.toPo(vo);
        user.setUpdateTime(DateTime.getCurrTime());
        int count = userDao.update(user);
        return count;
    }

    /**
     * 删除用户
     * @param id 用户ID
     * @return
     */
    public int delete(Integer id) throws ReadMessageException {
        logger.info("开始删除用户{}",id);
        return userDao.delete(id);
    }

    /**
     * 查找用户详情
     * @param id 用户ID
     * @return
     */
    public UserVo findByid(Integer id){
        User user = userDao.findById(id);
        if(user == null){
            return null;
        }
        UserVo vo = BeanUtil.toVo(user);
        return vo;
    }
}
